package com.lcpay.download.core;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 类AbstractHttpConnection.java的实现描述：httpUrlConnection 管理类
 * 
 * @author chenrs 2015年12月7日 下午11:24:45
 */
public abstract class AbstractHttpConnection extends AbstractMonitor {

    private static Logger     logger        = LoggerFactory.getLogger(AbstractHttpConnection.class);

    protected String          url;

    private HttpURLConnection httpURLConnection;

    private int               contentLength = -1;

    public AbstractHttpConnection(String url) {
        super();
        this.url = url;
    }

    /**
     * 长度
     * 
     * @return
     */
    protected int getContentLength() {
        if (contentLength != -1) {
            return contentLength;
        }

        if (null == httpURLConnection) {
            initHttpUrlConnection();
        }
        contentLength = httpURLConnection.getContentLength();
        return contentLength;

    }

    /**
     * 初始化
     */
    protected synchronized void initHttpUrlConnection() {
        if (null == httpURLConnection) {
            URL resouceUrl;
            try {
                resouceUrl = new URL(url);
                httpURLConnection = (HttpURLConnection) resouceUrl.openConnection();
            } catch (IOException e) {
                logger.error("初始化连接", e);
            }
        }
    }

    /**
     * 获取连接
     * 
     * @return
     */
    protected HttpURLConnection getUrlConnection() {
        if (null == httpURLConnection) {
            initHttpUrlConnection();
        }
        return httpURLConnection;
    }

    /**
     * 创建一个新的http 连接
     * 
     * @return
     */
    protected HttpURLConnection getNewConnection() {
        HttpURLConnection httpURLConnection = null;
        try {
            URL resouceUrl = new URL(url);
            httpURLConnection = (HttpURLConnection) resouceUrl.openConnection();
        } catch (IOException e) {
            logger.error("传教新的连接发生异常", e);
        }
        return httpURLConnection;
    }

    /**
     * 关闭连接
     */
    protected void closeHttpConnection() {
        if (null != httpURLConnection) {
            httpURLConnection.disconnect();
            httpURLConnection = null;
        }
    }

}
